package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.query.TravelQuery;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.repository.TravelRepository;
import cn.wolfcode.wolf2w.repository.UserInfoRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.JsonResult;
import cn.wolfcode.wolf2w.util.TravelCondition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
//@Transactional
public class TravelServiceImpl implements ITravelService {

    //操作MongoDB数据库
    @Autowired
    private TravelRepository travelRepository;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IDestinationService destinationService;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void save(Travel travel) {
        travel.setId(null);
        travelRepository.save(travel);
    }

    @Override
    public void delete(String id) {
        travelRepository.deleteById(id);
    }

    @Override
    public void update(Travel travel) {
        travelRepository.save(travel);
    }


    @Override
    public Travel findByOne(String id) {
        Optional<Travel> op = travelRepository.findById(id);
        Travel travel=null;
        if (op.isPresent()) {
            travel = op.get();
            //作者
            travel.setAuthor(userInfoService.findByOne(travel.getUserId()));
            //目的地
            travel.setDest(destinationService.findByOne(travel.getDestId()));
        }
        return travel;
    }

    /**
     * 查询点击量前3的游记文章
     * @param destId
     * @return
     */
    @Override
    public List<Travel> queryTravelsViewnumTop3ByDestId(String destId) {
        PageRequest pageRequest = PageRequest.of(0, 3, Sort.Direction.DESC, "thumbsupnum");
        return travelRepository.queryByDestId(destId,pageRequest);
    }

    @Override
    public void saveOrUpdate(Travel travel) {
        AssertUtil.hasObject("格式不正确",travel);
        //发布时间
        travel.setReleaseTime(new Date());
        //修改时间
        travel.setLastUpdateTime(new Date());
        //目的地名字
        Destination destination = destinationService.findByOne(travel.getDestId());
        travel.setDestName(destination.getName());
        if (StringUtils.hasLength(travel.getId())) {
            Travel queryTravel = this.findByOne(travel.getId());
            travel.setViewnum(queryTravel.getViewnum());
            travel.setReplynum(queryTravel.getReplynum());
            travel.setFavornum(queryTravel.getFavornum());
            travel.setSharenum(queryTravel.getSharenum());
            travel.setThumbsupnum(queryTravel.getThumbsupnum());
            this.update(travel);
        } else {
            //发布时间
            travel.setCreateTime(new Date());
            this.save(travel);
        }
    }

    /**
     * 审核
     * @param id
     * @param state
     */
    @Override
    public void audit(String id, int state) {
        AssertUtil.hasLength("参数不能不为空",id);
        Query query = new Query();
        Update update=new Update();
        query.addCriteria(Criteria.where("_id").is(id));
        if (Travel.STATE_REJECT==state) {
            //审核未通过
            update.set("state", state);
            update.set("lastUpdateTime",new Date());
        } else if (Travel.STATE_RELEASE==state) {
            //审核通过
            update.set("state", state);
            update.set("releaseTime", new Date());
            update.set("lastUpdateTime", new Date());
        } else {
            throw new LogicException("请输入正确的参数");
        }
        mongoTemplate.updateMulti(query,update,Travel.class);
    }


    /**
     * 高查
     * @param qo
     * @return
     */
    @Override
    public Object query(TravelQuery qo) {
        //创建查询对象
        Query query = new Query();
        //数据总条数
        long count = mongoTemplate.count(query, Travel.class);
        if (count==0) {
            //如果没有数据,返回空Page对象
            return Page.empty();
        }
        //查询天数
        TravelCondition day = TravelCondition.DAY_MAP.get(qo.getDayType());
        if (day!=null) {
            query.addCriteria(Criteria.where("day").gte(day.getMin()).lte(day.getMax()));
        }
        //人均消费
        TravelCondition consume = TravelCondition.CONSUME_MAP.get(qo.getPerExpendType());
        if (consume!=null) {
            query.addCriteria(Criteria.where("perExpend").gte(consume.getMin()).lte(consume.getMax()));
        }
        count=mongoTemplate.count(query,Travel.class);
        PageRequest pageRequest = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.DESC, qo.getOrderType()==2?"viewnum":"createTime");
        //添加页请求对象
        query.with(pageRequest);
        //查询数据库
        List<Travel> list = mongoTemplate.find(query, Travel.class);
        for (Travel travel : list) {
            //给作者设值
            travel.setAuthor(userInfoService.findByOne(travel.getUserId()));
        }
        return new PageImpl<>(list,pageRequest,count);
    }
    

    @Override
    public List<Travel> findAll() {
        return travelRepository.findAll();
    }
}
